
import UIKit


typealias SendBlock = (_ xid:NSString,_ msg:NSString ) -> Void

typealias refreshUnreadBlock = () -> Void

class TF_LivingService: TalkfunHitTestView, UITextFieldDelegate {
    @objc public var sendBlock: SendBlock?
    
    @objc public var unreadBlock: refreshUnreadBlock?
    
    @objc public let view = UIView()
    @objc public let pageScrollView = UIScrollView()
    @objc public let textField = UITextField()
    //发图片给客服
    @objc public let photoSend = UIButton()
    @objc public let currentButton = TF_LivingServiceButton()
    @objc public let page1 = TF_LivingServicePageView()
    
    var KeyboardHeight:CGFloat = 0
    let backButton2 = UIButton()
    let title2 = UILabel()
    let table2 = TF_livingTableView()
    let bottomView = UIView()
    let page2 = UIView()
    let inputFieldBackgroundColorView = UIView()
    let resignFirstResponderButton = UIButton()
   
    @objc func backButton2Click()
    {
        self.pageScrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        if(self.unreadBlock != nil)
        {
            self.unreadBlock!();
        }
    }
    @objc func resignFirstResponderButtonClcik()
    {
        self.textField.resignFirstResponder()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.view.frame = CGRect(x: 0, y: self.frame.height-433.0, width: self.frame.width, height: 433.0)
        
        self.pageScrollView.frame = self.view.bounds
        self.pageScrollView.contentSize = CGSize(width: self.pageScrollView.frame.size.width*2, height: self.pageScrollView.frame.size.height)
    
        self.page1.frame = self.pageScrollView.bounds
        self.page2.frame = CGRect(x: self.pageScrollView.frame.size.width, y: 0, width: self.pageScrollView.frame.size.width, height: self.pageScrollView.frame.size.height)
    
        self.resignFirstResponderButton.frame = self.page2.bounds
        
        self.backButton2.frame = CGRect(x: self.page2.frame.size.width - 32 - 6, y: 6, width: 32, height: 32)
        self.title2.frame = CGRect(x: 0, y: 20, width: self.page2.frame.size.width, height: 26)
     
        var bottomVieH:CGFloat = 92 - 32
        if (self.isNotchScreen) {
            bottomVieH = 92
        }
       
        self.table2.frame = CGRect(x: 0, y: 56, width: self.page2.frame.size.width, height: self.page2.frame.size.height - 56 - bottomVieH)
       
        
        self.bottomView.frame = CGRect(x: 0, y: self.page2.frame.size.height - bottomVieH, width: self.page2.frame.size.width, height: bottomVieH)
        
        self.bottomView.backgroundColor = UIColor(red: 255/255.0 , green: 255/255.0 , blue: 255/255.0 , alpha: 1.0)
    
        self.bottomView.layer.shadowColor = UIColor(red: 242/255.0 , green: 242/255.0 , blue: 242/255.0 , alpha: 1.0).cgColor
        
        self.bottomView.layer.shadowOffset = CGSize(width: 0, height: -1)
        
        self.bottomView.layer.shadowRadius = 0
        self.bottomView.layer.shadowOpacity = 1
        
        self.inputFieldBackgroundColorView.frame = CGRect(x: 12, y: 9, width: self.bottomView.frame.size.width - 12 - 12, height: 40)
        self.inputFieldBackgroundColorView.layer.cornerRadius = self.inputFieldBackgroundColorView.frame.size.height/2
        
        self.photoSend.frame = CGRect(x: self.inputFieldBackgroundColorView.frame.size.width - 22 - 16, y: (self.inputFieldBackgroundColorView.frame.size.height - 22)/2, width: 22, height: 22)
        self.textField.frame = CGRect(x: 14, y: 0, width: self.inputFieldBackgroundColorView.frame.size.width - 14 - 14 , height: self.inputFieldBackgroundColorView.frame.size.height)
        
        self.view.maskPath_new(size: CGSize(width: 12, height: 12))
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.photoSend.isHidden = true
        //键盘显示前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.KeyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        self.addSubview(self.view)
        self.view.backgroundColor = UIColor(red: 245/255.0 , green: 246/255.0 , blue: 248/255.0 , alpha: 1.0)

        self.pageScrollView.isScrollEnabled = false
        self.pageScrollView.isPagingEnabled = true
        self.view.addSubview(self.pageScrollView)
        
      
        self.pageScrollView.addSubview(self.page1)
        
        self.page1.didSelectBlock = {[weak self](model:TFMember) in
            
            self!.title2.text = model.nickname;
            
            self!.pageScrollView.setContentOffset(CGPoint(x: self!.pageScrollView.frame.size.width, y: 0), animated: true)
            
            
            //读取聊天列表
            let customerService = self!.page1.customerServiceDict[model.xid] as! TF_CustomerService;
            self!.table2.xid = model.xid as NSString;
            self!.table2.addChatList(list: customerService.chatList)
     
            guard self != nil else {
                return
            }
        }
        
        self.backgroundColor = UIColor.clear
        

        
        self.page2.backgroundColor = UIColor.clear
        self.pageScrollView.addSubview(self.page2)
        

        self.page2.addSubview(self.backButton2)
        self.backButton2.setImage(UIImage.init(named: "HTLive.bundle/backlisttoupiao"), for: .normal)
        self.backButton2.addTarget(self, action: #selector(self.backButton2Click), for: .touchUpInside)
    
        self.title2.numberOfLines = 0;
        self.page2.addSubview(self.title2)
        self.title2.textAlignment = .center;
  
        self.title2.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1.0)

        self.title2.font = UIFont.PingFang(size: 19)
        self.table2.backgroundColor = UIColor.clear
        self.page2.addSubview(self.table2)
        
        self.resignFirstResponderButton.isUserInteractionEnabled = false
        self.resignFirstResponderButton.addTarget(self, action: #selector(self.resignFirstResponderButtonClcik), for: .touchUpInside)
      
        self.page2.addSubview(self.resignFirstResponderButton)
        self.page2.addSubview(self.bottomView)
        
        //输入栏背景
        self.bottomView.addSubview(self.inputFieldBackgroundColorView)
        self.inputFieldBackgroundColorView.backgroundColor = UIColor(red: 241/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1.0)
       
       //发图片给客服
        self.photoSend.setImage(UIImage.init(named: "HTLive.bundle/sendpicto"), for: .normal)
        self.inputFieldBackgroundColorView.addSubview(self.photoSend)
    
        self.textField.delegate = self
        self.textField.returnKeyType = .send
        self.textField.enablesReturnKeyAutomatically = true
        self.inputFieldBackgroundColorView.addSubview(self.textField)
        
        self.textField.attributedPlaceholder = NSMutableAttributedString.getAttributed(string: "向老师私聊...", font: UIFont.PingFang(size: 16), foregroundColor: UIColor(red: 183/255.0, green: 187/255.0, blue: 191/255.0, alpha: 1.0));
    }
    @objc func keyboardWillShow(noti:NSNotification) {

       //不是聊天不用处理
        
        if (self.currentTextView(self.textField) == true) {
            self.resignFirstResponderButton.isUserInteractionEnabled = true

        }else{
            
            return;
            
        }
        let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
        
        let keyboardFrameEnd:NSValue = keyboardInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
        
        let frame:CGRect = keyboardFrameEnd.cgRectValue
        self.KeyboardHeight = frame.size.height;
    

       // 修改底部约束
        let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - frame.size.height - self.frame.size.height
   
        let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
        //  执行动画
        let duration = animationDuration.floatValue
        UIView.animate(withDuration: TimeInterval(duration)) {
            self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.size.height)
        }
    }
    
    @objc func KeyboardWillHide(noti:NSNotification) {

        if self.resignFirstResponderButton.isUserInteractionEnabled {
            if (self.currentTextView(self.textField) == true) {
                self.resignFirstResponderButton.isUserInteractionEnabled = false

                let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
                
                let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
                //  执行动画
                let duration = animationDuration.floatValue
                
                let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - self.frame.size.height;
                
                UIView.animate(withDuration: TimeInterval(duration)) {
                    self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.size.height)
                }

            }
        }
      
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //回车
           if (string == "\n") {
               if (self.sendBlock != nil) {
                   self.sendBlock!(self.table2.xid, self.textField.text! as NSString)
               }
                 return false;
           }
           
        return true
    }
    //返回所有在线的客服人员数据
   @objc public func updateXidUI(list:NSMutableArray)
    {
        self.page1.updateXidUI1(list: list as! [TFMember])
        
        for i in stride(from: 0, to: list.count ,by: 1) {
            let model:TFMember = list[i] as! TFMember
            
            self.getCustomerServiceModel(chat: nil, xid: model.xid as NSString )
        }
    }
    //添加聊天数据
   @objc public func addChatUI(chat:TFChatData,xid:NSString)
    {
       
        let model:TF_CustomerService = self.getCustomerServiceModel(chat: chat, xid: xid)
        //刚好在客服列表页
        if (self.pageScrollView.contentOffset.x == 0 ) {
         model.unread =  model.unread + 1;
         model.timestamp = chat.time as NSString;
         model.typeMsg = chat.msg;
        }else{
       
        //当前私聊内容页 是当前 客服
        if ( self.table2.xid == xid ) {
            //清空未读显示
            model.unread =  0;
            model.timestamp = "0";
            model.typeMsg = "";
            //读取聊天列表
            self.table2.addChatList(list: model.chatList)
      
        }else{
            model.unread =  model.unread + 1;
            model.timestamp = chat.time as NSString;
            model.typeMsg = chat.msg;
        }
        }
        self.page1.tableview.reloadData()
     
    }

    @objc public func destroySharedIntance()
    {
        NotificationCenter.default.removeObserver(self)
    }
    
    func getCustomerServiceModel(chat:TFChatData?,xid:NSString) ->TF_CustomerService
    {
        if ((self.page1.customerServiceDict[xid]) != nil) {
            //添加聊天记录
            let model:TF_CustomerService = self.page1.customerServiceDict[xid] as! TF_CustomerService
            if (chat == nil) {
              
            }else
            {
                model.chatList.add(chat as Any)
            }
          
            return model
        }else{
            let model = TF_CustomerService()
            if (chat == nil) {
              
            }else
            {
                model.chatList.add(chat as Any)
            }
            
            self.page1.customerServiceDict.setObject(model, forKey: xid)
            
            return model;
        }
     
    }
}
